const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')
const { Forbidden } = require('../core/http-exception')
const { server } = require('../config')
const { User } = require('../models')

const USER = 8
const ADMIN = 16
const SP_ADMIN = 32

function getLevel(scope = 1) {
  return scope <= USER ? 'USER' : 
         scope <= ADMIN ? 'ADMIN' : 
         scope <= SP_ADMIN ? 'SP_ADMIN' : 
         'NULL'
}

function getScope(level = ''){
  return level == 'USER' ? USER :
         level == 'ADMIN' ? ADMIN :
         level == 'SP_ADMIN' ? SP_ADMIN :
         null
}


class Auth {
  constructor(level) {
    this.level = level || 1
  }

  async t(ctx, next) {
    const Token = basicAuth(ctx.req)

    if (Token && Token.name) {
      try {
        jwt.verify(Token.name, server.auth.secretKey)
      } catch (err) {
        await next()
        return
      }

      throw new Forbidden('这个操作只能游客使用')
    }

    await next()
  }

  get l(){
    return async (ctx, next) => {
      const Token = basicAuth(ctx.req)

      if(Token && Token.name){
        const user = await User.findOne({
          where: {
            token: Token.name
          }
        })

        let msg = '无效的Token'
        if (!user) {
          // throw new Forbidden(msg)
          await next();
          return;
        }

        try {
          var decode = jwt.verify(Token.name, server.auth.secretKey)
        } catch (err) {
          if (err.name === 'TokenExpiredError') {
            msg = 'Token已过期'
          }

          throw new Forbidden(msg)
        }

        if (decode.scope < this.level) {
          throw new Forbidden('权限不足')
        }

        ctx.auth = {
          id: parseInt(decode.id),
          uid: decode.uid,
          scope: parseInt(decode.scope)
        }
      }

      await next()
    }
  }

  get m() {
    return async (ctx, next) => {
      const Token = basicAuth(ctx.req)

      if (!Token || !Token.name) {
        throw new Forbidden('没有携带Token')
      }

      const user = await User.findOne({
        where: {
          token: Token.name
        }
      })

      let msg = '无效的Token'
      if (!user) {
        throw new Forbidden(msg)
      }

      try {
        var decode = jwt.verify(Token.name, server.auth.secretKey)
      } catch (err) {
        if (err.name === 'TokenExpiredError') {
          msg = 'Token已过期'
        }

        throw new Forbidden(msg)
      }

      if (decode.scope < this.level) {
        throw new Forbidden('权限不足')
      }

      ctx.auth = {
        id: parseInt(decode.id),
        uid: decode.uid,
        scope: parseInt(decode.scope)
      }

      await next()
    }
  }
}

module.exports = {
  Auth,
  USER,
  ADMIN,
  SP_ADMIN,
  getLevel,
  getScope
}
